package com.smm.web.vmc.controller.User;

import com.smm.web.vmc.domain.User;
import com.smm.web.vmc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhenghao on 2016/8/30.
 *
 */
@Slf4j
@Controller
public class LoginController {

    @Resource
    private UserService userService;

    @Resource
    private VdioController vdioController;


    @RequestMapping("/login.do")
    public ModelAndView login(){

        return new ModelAndView("login");
    }

    @RequestMapping("/submitlogin.do")
    public ModelAndView submitlogin(String account,String password,HttpServletRequest request){

        log.info("------------in login account:"+account+" password:"+password);

        ModelAndView mv;

        //会员登录
        try {

            //检查账号、密码是否为空
            if(StringUtils.isBlank(account) || StringUtils.isBlank(password)) throw new Exception("登录账号、密码为空");

            User user = userService.login(account, password);

            //检查用户是否存在
            if(user==null) throw new Exception("登录账号、密码不正确");

            //登录成功，用户id保存到session
            request.getSession().setAttribute(UserService.USER_SESSION_KEY,user);

            //跳转到视频列表页面
            mv = vdioController.list(request);

        } catch (Exception e) {

            e.printStackTrace();

            mv = new ModelAndView("login");

            mv.addObject("err_msg",e.getMessage());

            log.error(String.valueOf(e));
        }

        return mv;

    }

}
